package com.hdoit.ares.web.tp.zzb.controllers;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.insu.service.IFanhuaAccidentService;
import com.hdoit.ares.logical.insu.service.IFanhuaCarService;
import com.hdoit.ares.logical.insu.service.IZhonganAccidentService;
import com.hdoit.ares.logical.insu.service.IZhonganCarService;
import com.hdoit.ares.logical.tp.model.ZhonganCallback;
import com.hdoit.ares.logical.tp.service.IZhonganCallbackService;
import com.hdoit.ares.logical.tp.zzb.model.AccidentCallback;
import com.hdoit.ares.logical.tp.zzb.model.ZzbDataCallback;
import com.hdoit.ares.logical.tp.zzb.service.IAccidentCallbackService;
import com.hdoit.ares.logical.tp.zzb.service.IZzbDataCallbackService;
import com.hdoit.ares.selfcommon.thirdparty.zzb.service.IZzbService;
import com.hdoit.ares.selfcommon.thirdparty.zzb.utils.YLAUtil;
import com.hdoit.ares.selfcommon.thirdparty.zzb.utils.ZzbConfiguration;
import com.hdoit.ares.selfcommon.thirdparty.zzb.utils.ZzbManageContainer;
import com.tennetcn.component.web.BaseController;
import com.tennetcn.web.cbase.AuthPassport;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.log.dialect.log4j2.Log4j2LogFactory;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.zhongan.scorpoin.common.ZhongAnNotifyClient;
import com.zhongan.scorpoin.common.ZhongAnOpenException;

@Controller
@RequestMapping(value = "/zzb/")
@AuthPassport
public class ZzbController extends BaseController {

	@Override
	public String getRoutePath() {
		return "areas/zzb/";
	}

	private IZzbService zzbService;

	public IZzbService getZzbService() {
		return zzbService;
	}

	@Resource
	public void setZzbService(IZzbService zzbService) {
		this.zzbService = zzbService;
	}

	private IZzbDataCallbackService zzbDataCallbackService;

	public IZzbDataCallbackService getZzbDataCallbackService() {
		return zzbDataCallbackService;
	}

	@Resource
	public void setZzbDataCallbackService(IZzbDataCallbackService zzbDataCallbackService) {
		this.zzbDataCallbackService = zzbDataCallbackService;
	}
	
	private IFanhuaAccidentService fanhuaAccidentService;	
	public IFanhuaAccidentService getAccidentInsuranceService() {
		return fanhuaAccidentService;
	}
	@Resource
	public void setAccidentInsuranceService(IFanhuaAccidentService fanhuaAccidentService) {
		this.fanhuaAccidentService = fanhuaAccidentService;
	}
	
	private IAccidentCallbackService  accidentCallbackService;
	public IAccidentCallbackService getAccidentCallbackService() {
		return accidentCallbackService;
	}
	@Resource
	public void setAccidentCallbackService(IAccidentCallbackService accidentCallbackService) {
		this.accidentCallbackService = accidentCallbackService;
	}

	private IFanhuaCarService carInsuranceService;
	public IFanhuaCarService getCarInsuranceService() {
		return carInsuranceService;
	}
	@Resource
	public void setCarInsuranceService(IFanhuaCarService carInsuranceService) {
		this.carInsuranceService = carInsuranceService;
	}
	
	private IZhonganCallbackService zhonganCallbackService;
	public IZhonganCallbackService getZhonganCallbackService() {
		return zhonganCallbackService;
	}
	@Resource
	public void setZhonganCallbackService(IZhonganCallbackService zhonganCallbackService) {
		this.zhonganCallbackService = zhonganCallbackService;
	}
	
	private IZhonganAccidentService zhonganAccidentService;
	public IZhonganAccidentService getZhonganAccidentService() {
		return zhonganAccidentService;
	}
	@Resource
	public void setZhonganAccidentService(IZhonganAccidentService zhonganAccidentService) {
		this.zhonganAccidentService = zhonganAccidentService;
	}
	
	private IZhonganCarService zhonganCarService;
	public IZhonganCarService getZhonganCarService() {
		return zhonganCarService;
	}
	@Resource
	public void setZhonganCarService(IZhonganCarService zhonganCarService) {
		this.zhonganCarService = zhonganCarService;
	}

	private final String indexViewName = "index";
	private final String callbackViewnName = "callback";
	private final String callbackprodViewnName = "callbackprod";
	private final String callbackywViewnName = "callbackyw";
	private final String callbackywprodViewnName = "callbackywprod";
	private final String callbackzacarViewName = "callbackzacar";
	private final String callbackzacarprodViewnName="callbackzacarprod";
	
	@ResponseBody
	@RequestMapping(value = indexViewName, method = { RequestMethod.GET, RequestMethod.GET })
	public void index(Model model, String userId, HttpServletResponse response) {
		String requestUrl = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.requestUrl);
		String authCode = zzbService.getInnerAuthCode(userId);

		String redirectUrl = requestUrl + authCode;
		redirectUrl += "&r=" + RandomUtil.randomNumbers(6);
		System.out.println("redirectUrl:" + redirectUrl);
		try {
			response.setDateHeader("Expires", 0);
			response.setHeader("Buffer", "True");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Expires", "0");
			response.setHeader("ETag", String.valueOf(System.currentTimeMillis()));
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Date", String.valueOf(new Date()));
			response.setHeader("Last-Modified", String.valueOf(new Date()));
			response.sendRedirect(redirectUrl);
		} catch (IOException e) {
			
		}
	}

	//泛华测试环境车险
	@ResponseBody
	@RequestMapping(value = callbackViewnName, method = { RequestMethod.GET, RequestMethod.POST })
	public String callback(@RequestBody String requestBody){
//	public String callback(HttpServletRequest request) throws IOException {
//		// 测试回调
//		BufferedReader br = request.getReader();
//		String str, requestBody = "";
//		while ((str = br.readLine()) != null) {
//			requestBody += str;
//		}
		Log4j2LogFactory.get().error("requestBody-prod:" + requestBody);
		System.out.println("requestBody:" + requestBody);
		ZzbDataCallback zzbDataCallback = zzbDataCallbackService.resolveZzbCallback(requestBody);
		try {
			carInsuranceService.fanhuaCarCallback(zzbDataCallback);
		} catch (Exception e) {
			e.getStackTrace();
		}

		if (!zzbDataCallbackService.applyChange(zzbDataCallback)) {
			return "saveing error";
		}
		return "ok";
	}

	// 泛华正式环境车险
	@ResponseBody
	@RequestMapping(value = callbackprodViewnName, method = { RequestMethod.GET, RequestMethod.POST })
	public String callbackprod(@RequestBody String requestBody){ 
		// 真实回调
		Log4j2LogFactory.get().error("requestBody-prod:" + requestBody);
		ZzbDataCallback zzbDataCallback = zzbDataCallbackService.resolveZzbCallback(requestBody);		
		try {
			carInsuranceService.fanhuaCarCallback(zzbDataCallback);
		} catch (Exception e) {
			e.getStackTrace();
			Log4j2LogFactory.get().error(e);
		}
		if (zzbDataCallback == null) {
			return "data is null";
		}
		if (!zzbDataCallbackService.applyChange(zzbDataCallback)) {
			return "saveing error";
		}
		return "ok";
	}

	// 泛华意健险测试
	@ResponseBody
	@RequestMapping(value = callbackywViewnName, method = { RequestMethod.GET, RequestMethod.POST })
	public String callbackyw(String returnStatus, String status, String orderSn, String recommendId) {
		// 测试回调
		// 根据订单号查找订单详情
		//orderSn = "17906348pUGx9C12";
		getZzbOrderInfo(orderSn);
		return "ok";
	}

	// 泛华意健险正式
	@ResponseBody
	@RequestMapping(value = callbackywprodViewnName, method = { RequestMethod.GET, RequestMethod.POST })
	public String callbackywprod(String returnStatus, String status, String orderSn, String recommendId) {
		// 真实回调
		// 根据订单号查找订单详情
		getZzbOrderInfo(orderSn);
		return "Ok";
	}
	
	private String getZzbOrderInfo(String orderSn) {
		String url = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.accidentUrl);
		String channeId = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.accidentChannelId);
		String password = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.accidentPassword);
		String channelName = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.accidentChannelName);
		String cSrc = "{\"header\":{\"channelId\":\"" + channeId + "\",\"channelName\":\"" + channelName + "\",\"password\":\"" + password + "\"},\"body\":{\"orderInfo\":{\"orderId\":\"" + orderSn + "\"}}}";
		String enString = YLAUtil.encrypt(cSrc);
		url += enString;
		String body = HttpUtil.get(url);
		String accident = YLAUtil.decrypt(body);
		Log4j2LogFactory.get().error("accident:" + accident);
		AccidentCallback accidentCallback = accidentCallbackService.resolveAccidentCallback(accident, orderSn);
		try {
			fanhuaAccidentService.accidentCallback(accidentCallback);
		} catch (Exception e) {
			e.getStackTrace();
		}
		if (accidentCallback == null) {
			return "accidentCallback is null";
		}
		if (!accidentCallbackService.applyChange(accidentCallback)) {
			return "saveing error";
		}
		return accident;
	}

	//众安回调 测试
	@ResponseBody
	@RequestMapping(value = callbackzacarViewName, method = { RequestMethod.GET, RequestMethod.POST })
	public String callbackzacar(HttpServletRequest request) throws ZhongAnOpenException {
		//众安加密参数
		//String zhongan_publickKey = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.zhongan_publicKey);
		String putiyoli_privateKey = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.putiyoli_privateKey);
		// 使用环境参数（dev、iTest、uat、prd）和开发者私钥初始化
		ZhongAnNotifyClient notify = new ZhongAnNotifyClient("uat", putiyoli_privateKey); // PRK// =开发者私钥
		
		// 获取参数
		Map<String, String[]> map = request.getParameterMap();
		// 解密验签，若以流传参，可先解析参数，转为JSONObject
		// 再调用parseNotifyRequest(JSONObject params)方法
		String result = notify.parseNotifyRequest(map);
		try {
			request.setCharacterEncoding( "UTF-8" );
		} catch (UnsupportedEncodingException e1) {
			Log4j2LogFactory.get().error("数据格式错误");
		}
		Log4j2LogFactory.get().error(result);
		ZhonganCallback zhonganCallback =zhonganCallbackService.resolveZhonganCallback(result);
		try {
			String bizContent = zhonganCallback.getBizContent();
			Log4j2LogFactory.get().error("bizContent+++++"+bizContent);
			if(bizContent.length()<100){
				zhonganAccidentService.zhonganAccidentCallback(zhonganCallback);
			}else if(bizContent.length()>=100){
				Log4j2LogFactory.get().error("+++++进入车险解析+++++");
				zhonganCarService.zhonganCarCallback(zhonganCallback);			
			}
		} catch (Exception e) {
			Log4j2LogFactory.get().error("众安数据解析失败");
		}
		
	/*	String openKey =ZzbConfiguration.getInstance().getValue(ZzbManageContainer.zhongan_openKey);
		String a = "a5f4b2b813285f595f227aca103020d7c4166d7c526eb8990398c12ca2f5300ae03aa2f18fe73796d65d0d050995ebd9d23e40a42c8561a54ad8522c74eb07d081b1899599742048c63043e498fedde82a9b710c97d81ec23c87dbff5d3071aacbeb98ae199f54e2f1996f6754dc56ae05d4ea8288767e4f95427bb4cfc9d866697e3eb60c96727183a5724dbceedbbb902e6b811edd3360f0f35d37ac38a6f11e8b555b4535fd7dc2be042102d23ef0431f71d04a79756f4aed4b0293ba5d6e6303feaccb544d071e352c70977a769604ddd164f89f3d2bc69bffa3206949b50536987d2bbf9849a35276cd517a42c7061a26cdfdbda1d407c3da33b2741fd89b310145b8c3caedf3b404bd67bbf13c0847c5c022daf9c009629a948c6c1a6614674f39a3f607b9a64f5b3eb005fac4712c48b5d65e5e19339bc9c97653d52428e7589e40d796035cc3448322f77d200ffcc32657212be873f73841831b7218edf8b5782d9543fc4e7113e524a12ec6e10a0bd34ca145a33014fe6548e96de366ac2b810050ca8b79b41a33bc3b00520220e2d5f3452ae664c294da1406f22296a789c93f98fc07c72537b1c66678c319df02beb8778765679dc00632cb3e1c6de63809dc72d2c1facf50ef8513e2e2bfd2659e3a9cce1d9183101e93c0b6ae7bce43b2d6f0bc1da2a7f24e32b65bbb257b11633cbf0553d83739fe06dfd89694a74e129890956ae890f90aa931c85dd87a09e2";
		String b = RC4Util.decryRC4(a, openKey);
		String c = RC4Util.decryRC4(a, openKey);
		Log4j2LogFactory.get().error("aaaaaaaaaaa++++0"+b);
		Log4j2LogFactory.get().error("aaaaaaaaaaa++++0"+c);
		String encoding = System.getProperty("file.encoding"); 
		Log4j2LogFactory.get().error(encoding);*/
		
		if (zhonganCallback == null) {
			throw new RuntimeException("zhonganCallback is  null");
		}
		if (!zhonganCallbackService.applyChange(zhonganCallback)) {
			Log4j2LogFactory.get().error("zhonganCallback save error");
		}
		String res = notify.buildNotifyResponse("success");
		System.out.println(res);
		return "success";
	}
	
	// 众安真实回调 
	@ResponseBody
	@RequestMapping(value = callbackzacarprodViewnName, method = { RequestMethod.GET, RequestMethod.POST })
	public String callbackzacarprod(HttpServletRequest request) throws ZhongAnOpenException {
		// 众安加密参数
		// String zhongan_publickKey =
		// ZzbConfiguration.getInstance().getValue(ZzbManageContainer.zhongan_publicKey);
		String putiyoli_privateKey = ZzbConfiguration.getInstance().getValue(ZzbManageContainer.putiyoli_privateKey);
		// 使用环境参数（dev、iTest、uat 测试、prd 正式）和开发者私钥初始化
		ZhongAnNotifyClient notify = new ZhongAnNotifyClient("prd", putiyoli_privateKey); // PRK//// =开发者私钥
		
		// 获取参数
		Map<String, String[]> map = request.getParameterMap();
		// 解密验签，若以流传参，可先解析参数，转为JSONObject
		// 再调用parseNotifyRequest(JSONObject params)方法
		try {
			request.setCharacterEncoding( "UTF-8" );
		} catch (UnsupportedEncodingException e1) {
			Log4j2LogFactory.get().error("数据格式错误");
		}
		String result = notify.parseNotifyRequest(map);
		Log4j2LogFactory.get().error("result+++"+result);
		
/*		String openKey =ZzbConfiguration.getInstance().getValue(ZzbManageContainer.zhongan_openKey);
		String a = "a5f4b2b813285f595f227aca103020d7c4166d7c526eb8990398c12ca2f5300ae03aa2f18fe73796d65d0d050995ebd9d23e40a42c8561a54ad8522c74eb07d081b1899599742048c63043e498fedde82a9b710c97d81ec23c87dbff5d3071aacbeb98ae199f54e2f1996f6754dc56ae05d4ea8288767e4f95427bb4cfc9d866697e3eb60c96727183a5724dbceedbbb902e6b811edd3360f0f35d37ac38a6f11e8b555b4535fd7dc2be042102d23ef0431f71d04a79756f4aed4b0293ba5d6e6303feaccb544d071e352c70977a769604ddd164f89f3d2bc69bffa3206949b50536987d2bbf9849a35276cd517a42c7061a26cdfdbda1d407c3da33b2741fd89b310145b8c3caedf3b404bd67bbf13c0847c5c022daf9c009629a948c6c1a6614674f39a3f607b9a64f5b3eb005fac4712c48b5d65e5e19339bc9c97653d52428e7589e40d796035cc3448322f77d200ffcc32657212be873f73841831b7218edf8b5782d9543fc4e7113e524a12ec6e10a0bd34ca145a33014fe6548e96de366ac2b810050ca8b79b41a33bc3b00520220e2d5f3452ae664c294da1406f22296a789c93f98fc07c72537b1c66678c319df02beb8778765679dc00632cb3e1c6de63809dc72d2c1facf50ef8513e2e2bfd2659e3a9cce1d9183101e93c0b6ae7bce43b2d6f0bc1da2a7f24e32b65bbb257b11633cbf0553d83739fe06dfd89694a74e129890956ae890f90aa931c85dd87a09e2";
		String b = RC4Util.decryRC4(a, openKey);		
		Log4j2LogFactory.get().error("aaaaaaaaaaa++++0"+b);*/
		
		ZhonganCallback zhonganCallback =zhonganCallbackService.resolveZhonganCallback(result);
		try {
			String bizContent = zhonganCallback.getBizContent();
			Log4j2LogFactory.get().error("bizContent+++++"+bizContent);
			if(bizContent.length()<100){
				zhonganAccidentService.zhonganAccidentCallback(zhonganCallback);
			}else if(bizContent.length()>=100){
				Log4j2LogFactory.get().error("+++++进入车险解析+++++");
				zhonganCarService.zhonganCarCallback(zhonganCallback);			
			}
		} catch (Exception e) {
			Log4j2LogFactory.get().error("众安数据解析失败");
		}
		if (zhonganCallback == null) {
			throw new RuntimeException("zhonganCallback is  null");
		}
		if (!zhonganCallbackService.applyChange(zhonganCallback)) {
			Log4j2LogFactory.get().error("zhonganCallback save error");
		}
		String res = notify.buildNotifyResponse("success");
		System.out.println(res);
		return "success";
	}
}
